﻿CREATE PROCEDURE [dbo].[yaf_pmessage_prune](
                @DaysRead   INT,
                @DaysUnread INT)
AS
    BEGIN
        DELETE FROM yaf_UserPMessage
        WHERE       IsRead <> 0
        AND Datediff(dd,(SELECT Created
                         FROM   yaf_PMessage x
                         WHERE  x.PMessageID = yaf_UserPMessage.PMessageID),
                     Getdate()) > @DaysRead
        DELETE FROM yaf_UserPMessage
        WHERE       IsRead = 0
        AND Datediff(dd,(SELECT Created
                         FROM   yaf_PMessage x
                         WHERE  x.PMessageID = yaf_UserPMessage.PMessageID),
                     Getdate()) > @DaysUnread
        DELETE FROM yaf_PMessage
        WHERE       NOT EXISTS (SELECT 1
                    FROM   yaf_UserPMessage x
                    WHERE  x.PMessageID = yaf_PMessage.PMessageID)
    END


